/*
  1.创建三个线程，都对 money 全局变量进行操作
  2.线程1每次对 money 加10
  3.线程2每次对 money 加0.01
  4.线程3读取 money 的值
*/

#include "spu.h"

float money;
//定义读写锁
pthread_rwlock_t rwlock;

void *thread_fun1(void *arg)
{
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock);  //加写锁
        money += 10;
        printf("01: money = %.2f\n",money);
        pthread_rwlock_unlock(&rwlock);  //解锁
        usleep(500000);  //500ms延时
    }
    return (void*)1;
}

void *thread_fun2(void *arg)
{
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock);  //加写锁
        money += 0.01;
        printf("02: money = %.2f\n",money);
        pthread_rwlock_unlock(&rwlock);  //解锁
        usleep(500000); 
    }
	return (void*)2;
}

void *thread_fun3(void *arg)
{
    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);  //加读锁
        printf("03: reade money = %.2f\n",money);
        pthread_rwlock_unlock(&rwlock);  //解锁
        usleep(500000);  //500ms延时
    }
	return (void*)3;
}

int main(int argc, char *argv[])
{	
	int err1, err2, err3;
	pthread_t thread_id1, thread_id2, thread_id3; 

    void *__retval;
    
    //首先初始化读写锁
    pthread_rwlock_init(&rwlock, NULL);

	err1 = pthread_create(&thread_id1, NULL, thread_fun1, NULL);
	if(err1 != 0)
		printf("create thread01 failed!\n");

    err2 = pthread_create(&thread_id2, NULL, thread_fun2, NULL);
	if(err2 != 0)
		printf("create thread02 failed!\n"); 

    err3 = pthread_create(&thread_id3, NULL, thread_fun3, NULL);
	if(err3 != 0)
		printf("create thread03 failed!\n"); 

    sleep(1);
    pthread_exit(__retval);
}

